//app.js
App({

  globalData: {
     userInfo: null,
     fileUrl: "https://operations.e-square.com.cn/images",
     //fileUrl: "http://192.168.1.16:8082/images",
     //url:"http://192.168.1.16:8080/WeChatController"
     url: "https://operations.e-square.com.cn/WeChatController"
    
  },

  onLaunch: function () {
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 登录
    wx.login({
      success: res => {
        var that = this;
        //  that.globalData.setStorageSync
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: that.globalData.url+'/loginWeChatUser.do',
          method:'POST',
          data:{
            vxCode: res.code
          },
          header:{ 
            'content-type': 'application/x-www-form-urlencoded'// 提交的数据类型 
          },
          success:function(res){//存入当前用户状态
            if (res.data.code==200){
              wx.setStorageSync('openid', res.data.data.openid);
              wx.setStorageSync('nickName', res.data.data.nickName);
              that.globalData.userInfo = res.data.data;
            }else{
              wx.setStorageSync('status', 1);
              wx.setStorageSync('openid', res.data.data);
              wx.reLaunch({
                url: '/pages/user/user'
              })
            }
          }, 
          fail() { // 失败回调
            console.log('error');
          }
        })
      }
    })

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
             // this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },

  getUserInfo: function (e) {
    let that = this;
    that.globalData.userInfo = e.detail.userInfo
    that.setData({
      userInfo: e.detail.userInfo
    })
    if (wx.getStorageSync("status") == 1) {
      wx.request({
        url: that.globalData.url +'/insertWeChatUser.do',
        method: 'POST',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          openid: wx.getStorageSync("openid")
        }, header:{
          'content-type': 'application/x-www-form-urlencoded'// 提交的数据类型 
        }, success: function (stu) {//存入当前用户状态
          
           //console.log(stu.data.msg);
        },
        fail() { // 失败回调
          //console.log('error');
        }
      })

    }
  }


})